<template>
  <!-- 弹出框 -->
  <el-dialog @close="cancle" title="新增员工" :visible="showDialog">
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-width="80px"
      style="width:75%;margin: 0 auto"
    >
      <el-form-item label="姓名" prop="username">
        <el-input
          placeholder="2-4个字符"
          v-model="form.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          placeholder="请输入手机号码"
          v-model="form.mobile"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <!-- 日期选择器 -->
        <el-date-picker
          style="width:100%"
          v-model="form.timeOfEntry"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select
          style="width:100%"
          v-model="form.formOfEmployment"
          placeholder="请选择"
        >
          <el-option
            v-for="item in hireType"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input
          placeholder="1-30个字符"
          v-model="form.workNumber"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-input
          placeholder="请选择部门"
          v-model="form.departmentName"
          autocomplete="off"
          @focus="showTreeData"
          @blur="handleBlur"
        ></el-input>
        <!-- 放一个tree来显示部门数据 -->
        <el-tree
          v-if="showTree"
          default-expand-all
          :data="departments"
          :props="defaultProps"
          @node-click="handleNodeClick"
          v-loading="treeLoading"
        ></el-tree>
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <!-- 日期选择器 -->
        <el-date-picker
          style="width:100%"
          v-model="form.correctionTime"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancle">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import enumObj from '@/api/constant/employees'
// 导入部门数据 addEmployee
import { getDepartments } from '@/api/departments'
import { getDepData } from '@/utils'
import { addEmployee } from '@/api/employees'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      hireType: enumObj.hireType,
      //   树状控件绑定的部门数据
      departments: [],
      //   显示部门输入框的树控件
      showTree: false,
      //  加载动画
      treeLoading: false,
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      form: {
        username: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        correctionTime: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 2, max: 4, message: '请输入2-4个字符', trigger: 'blur' }
        ],
        mobile: [{ required: true, message: '请输入', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请输入', trigger: 'blur' }],
        formOfEmployment: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        workNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        // 树状部门数据发生改变时才触发验证规则！！
        departmentName: [
          { required: true, message: '请输入', trigger: 'change' }
        ],
        correctionTime: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 部门输入框聚焦事件：
    async showTreeData () {
      // 显示树形结构
      this.showTree = true
      // 显示加载动画
      this.treeLoading = true
      // 聚焦输入框后，获取部门数据
      let res = await getDepartments()
      //   console.log(res)
      //   把转化为树状结构的数据给部门数据弹出框
      this.departments = getDepData(res.data.depts, '')
      this.treeLoading = false
    },
    // 树形控件子节点点击事件：
    // 参数一：被点的节点数据
    // 参数二：被点的节点对象
    // 参数三：被点的节点所在的tree组件对象
    handleNodeClick (data, node, tree) {
      //   console.log(data)
      //   console.log(node)
      //   console.log(tree)
      //   把被点的节点数据的name属性赋值给部门文本框
      this.form.departmentName = node.data.name
      this.showTree = false
    },
    // 部门输入框失去焦点事件：
    handleBlur (e) {
      //   console.log(e)
      //   e.relatedTarget事件对象里面的属性：失去焦点之后，取到了哪个元素。
      //   console.log(e.relatedTarget)
      //   如果失去焦点之后去到的不是部门的树状结构，就失去焦点
      if (e.relatedTarget.className.indexOf('el-tree-node') == -1) {
        this.showTree = false
      }
    },
    // 新增窗口的确认按钮：
    save () {
      // 整个表单验证 validate
      this.$refs.form.validate(async val => {
        // 验证通过发送新增请求
        if (val) {
          let res = await addEmployee(this.form)
          console.log(res)
          this.$message.success('新增员工成功！')
          // 告诉父组件弹出框隐藏
          //   错误示范：this.showDialog = false
          this.$emit('update:showDialog', false)
          // 告诉父组件重新加载数据
          //   数据新增在父组件的最后一页:（原本总数量+新增的1页）/页容量=最后一页。
          let pageInfo = this.$parent.pageInfo
          // 因为新增数据要加载到最后一页，所以要改变total
          pageInfo.total += 1
          let lastPage = Math.ceil(pageInfo.total / pageInfo.size)
          //  让父组件请求最后一页
          this.$parent.pageInfo.page = lastPage
          // 让父组件刷新数据
          // 如果是最后一页，并且只有一条数据。要加载上一页
          // if (this.form.length == 1 && pageInfo.page != 1) {
          //   pageInfo.page--
          // }
          this.$parent.getEmpList()
        }
      })
    },
    // 新增窗口取消按钮
    cancle () {
      this.$emit('update:showDialog', false)
      ;(this.form = {
        username: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        correctionTime: ''
      }),
        this.$refs.form.resetFields()
    }
  }
}
</script>

<style></style>
